package ch.il07.converter.presentation;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 * This class holds a few methods which are frequently used on the presentation layer.
 */
public class Helper {
	
	/**
	 * Gets the faces context.
	 * @return FacesContext object.
	 */
	public static FacesContext getFacesContext() {
		return FacesContext.getCurrentInstance();
	}
	
	/**
	 * Gets the external context.
	 * @return ExternalContext object.
	 */
	public static ExternalContext getExternalContext() {
		return getFacesContext().getExternalContext();
	}
	
	/**
	 * Gets the session for the current user.
	 * @return Session object
	 */
	public static HttpSession getSession() {
		return (HttpSession) getExternalContext().getSession(true);
	}

	/**
	 * Gets the username of the current user.
	 * @return String representing the username.
	 */
	public static String getUserName() {
		return (String) getSession().getAttribute("username");
	}
	
	/**
	 * Checks if the user is logged in/authenticated.
	 * @return true if user is logged in else false.
	 */
	public static boolean isAutenthicated() {
		return getUserName() != null;
	}
	
	/**
	 * Checks if the user is logged in/authenticated.
	 * @return true if user is not logged in else true.
	 */
	public static boolean isNotAuthenticated() {
		return !isAutenthicated();
	}
	
	/**
	 * Checks if the user is an administrator.
	 * @return true if user is an administrator.
	 */
	public static boolean isAdministrator() {
		return "true".equals(getSession().getAttribute("isAdministrator"));
	}
	
	public static ErrorHandler getErrorHandler() {
		ErrorHandler handler = (ErrorHandler) getSession().getAttribute("ErrorHandler");
		if(null == handler) {
			handler = new ErrorHandler();
			getSession().setAttribute("ErrorHandler", handler);
		}
		return handler;
	}
	
	public static String getErrors() {
		ErrorHandler handler = getErrorHandler();
		return handler.getErrors();
	}
}